package com.example.day12_7_12_2.base;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.day12_7_12_2.bean.NaviBean;
import com.example.day12_7_12_2.databinding.LayoutItemBinding;

import java.util.List;

public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseAdapter.ItemHolder> {
    private Context context;
    private List<T> list;

    public BaseAdapter(Context context, List<T> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayout(), parent, false);
        return new ItemHolder(view);
    }

    public abstract int getLayout();

    @Override
    public void onBindViewHolder(@NonNull ItemHolder holder, int position) {
        T t = list.get(position);
        bindData(holder,t);
    }

    protected abstract void bindData(ItemHolder holder, T t);
    //加载更多
    public void addData(List<T> list) {
        if (list != null && list.size() > 0) {
            this.list.addAll(list);
            notifyDataSetChanged();
        }
    }
    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ItemHolder extends RecyclerView.ViewHolder {

        SparseArray<View> mMap = new SparseArray<>();

        public ItemHolder(@NonNull View itemView) {
            super(itemView);
        }
        public View findView(@IdRes int id){
            View view = mMap.get(id);
            if (view == null){
                view = itemView.findViewById(id);
                mMap.put(id,view);
            }
            return view;
        }
    }
}
